using Microsoft.AspNetCore.Mvc;
using GroupSix.Application.Services;
using GroupSix.Application.Dtos;

namespace GroupSix.Api.Controllers;

/// <summary>
/// 权限控制控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class PermissionController : ControllerBase
{
    private readonly PermissionService _permissionService;

    public PermissionController(PermissionService permissionService)
    {
        _permissionService = permissionService;
    }

    /// <summary>
    /// 获取用户权限
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <returns>用户权限信息</returns>
    [HttpPost("user-permissions")]
    public async Task<IActionResult> GetUserPermissions([FromBody] GetUserPermissionsRequestDto request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .ToList();
            return BadRequest(new { success = false, message = "请求参数验证失败", errors });
        }

        var (success, message, data) = await _permissionService.GetUserPermissionsAsync(request);

        if (success)
        {
            return Ok(new { success = true, message, data });
        }
        else
        {
            return BadRequest(new { success = false, message });
        }
    }

    /// <summary>
    /// 验证用户权限
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <returns>权限验证结果</returns>
    [HttpPost("validate")]
    public async Task<IActionResult> ValidatePermission([FromBody] ValidatePermissionRequestDto request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .ToList();
            return BadRequest(new { success = false, message = "请求参数验证失败", errors });
        }

        var (success, message, data) = await _permissionService.ValidatePermissionAsync(request);

        if (success)
        {
            return Ok(new { success = true, message, data });
        }
        else
        {
            return BadRequest(new { success = false, message });
        }
    }

    /// <summary>
    /// 获取用户菜单
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <returns>用户菜单树</returns>
    [HttpPost("user-menus")]
    public async Task<IActionResult> GetUserMenus([FromBody] GetUserMenusRequestDto request)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage)
                .ToList();
            return BadRequest(new { success = false, message = "请求参数验证失败", errors });
        }

        var (success, message, data) = await _permissionService.GetUserMenusAsync(request);

        if (success)
        {
            return Ok(new { success = true, message, data });
        }
        else
        {
            return BadRequest(new { success = false, message });
        }
    }

    /// <summary>
    /// 检查用户是否有特定权限（GET方式，用于前端权限检查）
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="permissionKey">权限标识</param>
    /// <param name="menuPath">菜单路径</param>
    /// <returns>权限检查结果</returns>
    [HttpGet("check")]
    public async Task<IActionResult> CheckPermission(
        [FromQuery] Guid userId,
        [FromQuery] string permissionKey,
        [FromQuery] string? menuPath = null)
    {
        var request = new ValidatePermissionRequestDto
        {
            UserId = userId,
            PermissionKey = permissionKey,
            MenuPath = menuPath
        };

        var (success, message, data) = await _permissionService.ValidatePermissionAsync(request);

        if (success)
        {
            return Ok(new { success = true, message, data });
        }
        else
        {
            return BadRequest(new { success = false, message });
        }
    }

    /// <summary>
    /// 获取用户菜单（GET方式，用于前端获取菜单）
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>用户菜单树</returns>
    [HttpGet("menus/{userId}")]
    public async Task<IActionResult> GetUserMenusById(Guid userId)
    {
        var request = new GetUserMenusRequestDto
        {
            UserId = userId
        };

        var (success, message, data) = await _permissionService.GetUserMenusAsync(request);

        if (success)
        {
            return Ok(new { success = true, message, data });
        }
        else
        {
            return BadRequest(new { success = false, message });
        }
    }
} 